<template>
  <ve-card title="租赁信息" :customContentStyle="{ paddingBottom: 0 }" v-bind="$attrs">
    <template v-if="mode == 'edit' && orderStatus == 'orderInProgress'">
      <!-- 还车门店 -->
      <LeaseSite type="returnSite" ref="returnSiteRef" />
    </template>
    <template #forever-show v-if="mode != 'edit' || orderStatus != 'orderInProgress'">
      <ve-form-item prop="orderSource" required label="订单来源" v-if="orderStatus != 'orderCompleted'">
        <template v-if="mode == 'edit'">
          <text style="color: #cdced0">{{ form.orderSourceName }}</text>
        </template>
        <ve-picker-inline
          v-else
          v-model="form.orderSource"
          placeholder="请选择"
          :range="dict.orderSourceEnum"
          unit="arrowRight"
          @change="changeOrderSourceFn"
        />
      </ve-form-item>
      <ve-form-item prop="channelType" :required="form.orderSource == 2" label="订单渠道" v-if="operaOrderMaintenance(form)">
        <template v-if="mode == 'edit'">
          <text style="color: #cdced0">{{ form.channelTypeName }}</text>
        </template>
        <ve-picker-inline
          v-else
          :disabled="form.orderSource != 2"
          v-model="form.channelType"
          placeholder="请选择"
          :range="sysDict.short_order_channel_type"
          unit="arrowRight"
          @change="changeOrderChannelFn"
        />
      </ve-form-item>
    </template>

    <ve-form-item
      v-if="(mode != 'edit' || orderStatus != 'orderInProgress') && operaOrderMaintenance(form)"
      prop="channelOrderCode"
      :required="form.orderSource == 2"
      label="渠道单号"
    >
      <template v-if="mode == 'edit'">
        <text style="color: #cdced0">{{ form.channelOrderCode || '-' }}</text>
      </template>
      <template v-else>
        <ve-input v-if="form.orderSource != 2" disabled placeholderStyle="color: #cdced0" />
        <ve-input v-else v-model="form.channelOrderCode" :maxlength="32" />
      </template>
    </ve-form-item>
    <ve-form-item prop="orderAcquisitionType" label="订单获取方式">
      <!-- <template v-if="mode == 'edit'">
          <text style="color: #cdced0">{{ form.orderAcquisitionTypeName || '-' }}</text>
        </template>
        <template v-else> -->
      <remote-select
        type="order_acquisition"
        v-model="form.orderAcquisitionType"
        :label="form.orderAcquisitionTypeName"
        @change="changeOrderAcquisitionType"
      />
      <!-- <ve-picker-inline
            v-model="form.orderAcquisitionType"
            placeholder="请选择"
            :range="sysDict.short_order_acquisition_type"
            unit="arrowRight"
            @change="changeOrderAcquisitionType"
          /> -->
      <!-- </template> -->
    </ve-form-item>
    <template v-if="mode != 'edit' || (orderStatus != 'orderInProgress' && orderStatus != 'orderCompleted')">
      <ve-form-item labelPosition="top" prop="timeRange" required label="预计租赁周期" labelTooltipContent="租赁周期最小时间范围为1小时">
        <template #label-extra>
          <view style="color: #3072f6"> 租期：{{ form.rentDays || '- 天' }} </view>
        </template>
        <ve-daterange-picker
          v-model:start="form.startTime"
          v-model:end="form.endTime"
          :placeholder="['开始时间', '结束时间']"
          mode="datetime"
          @confirm="timeRangeConfirmFn"
        />
      </ve-form-item>
      <!-- 取车门店 -->
      <LeaseSite :mode="mode" type="site" ref="siteRef" :siteRequired="true" />
      <!-- 还车门店 -->
      <LeaseSite :mode="mode" type="returnSite" ref="returnSiteRef" />
      <!-- 车型选择 -->
      <ve-form-item prop="originalModelId" required label="车型" labelTooltipContent="请先选择租赁周期和取车门店后，再选择车型">
        <CustomSelect tip="请先选择租赁周期和取车门店后，再选择车型" @click="customSelectTap" :modelValue="form.originalModelName" />
      </ve-form-item>
      <ve-form-item label="订单备注" labelPosition="top" :borderBottom="false">
        <ve-input type="textarea" v-model="form.remark" :maxlength="200" />
      </ve-form-item>
    </template>
  </ve-card>
</template>
<script setup>
  import { ref, inject } from 'vue'
  import { computeRentDayAPI } from '@/api/order/sOrder'
  import LeaseSite from './lease/lease-site.vue'
  import CustomSelect from '../../components/custom-select.vue'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { serializeUrlParams } from '@/utils'
  import { useSysDict } from '@/hooks/useDict'
  import { operaOrderMaintenance } from '../../tools.js'
  const sysDict = useSysDict(['short_order_channel_type', 'short_order_acquisition_type'])

  defineProps({
    mode: {
      type: String,
      default: '',
    },
    orderStatus: {
      type: String,
      default: '',
    },
  })
  const form = inject('form')
  const dict = inject('dict')

  // 切换订单来源
  const changeOrderSourceFn = () => {
    form.value.channelType = undefined
    form.value.channelOrderCode = undefined
  }
  // 切换订单渠道
  const changeOrderChannelFn = () => {
    form.value.channelOrderCode = undefined
  }
  // 切换订单获取方式
  const changeOrderAcquisitionType = (val, option = {}) => {
    form.value.orderAcquisitionType = val
    form.value.orderAcquisitionTypeName = option.name
  }
  // 日期范围变化，并计算租期
  const timeRangeConfirmFn = (value = []) => {
    form.value.timeRange = value
    // 计算租期
    if (value[0] && value[1]) {
      const param = {
        startTime: value[0],
        endTime: value[1],
        siteId: form.value.siteId,
      }
      computeRentDayAPI(param).then((res) => {
        let { days } = res.result
        if (days.indexOf('小时') >= 0 && days.indexOf('天') >= 0) {
          days = days.replace('天', ' 天 ').replace('小时', ' 小时')
        } else {
          days = days.replace('天', ' 天').replace('小时', ' 小时')
        }
        form.value.rentDays = days
      })
    }
  }
  // 选择车型
  const customSelectTap = () => {
    let paramStr = serializeUrlParams({
      siteId: form.value.siteId,
      siteName: form.value.siteName,
      modelId: form.value.originalModelId,
      modelName: form.value.originalModelName,
      startTime: form.value.startTime,
      endTime: form.value.endTime,
    })
    uni.navigateTo({
      url: `/pages/asset/stock/model-stock/selector?${paramStr}`,
    })
  }
  // 编辑场景下，更新 ShortsiteConfig
  const siteRef = ref()
  const returnSiteRef = ref()
  const updateShortsiteConfig = (siteId, siteName, type) => {
    if (type == 'site') {
      siteRef.value ? siteRef.value.changeSiteIdFn(siteId, { siteName }, true) : ''
    }
    if (type == 'returnSite') {
      returnSiteRef.value ? returnSiteRef.value.changeSiteIdFn(siteId, { siteName }, true) : ''
    }
  }
  defineExpose({
    updateShortsiteConfig,
  })
  onLoad(() => {
    // 车型选择完成
    uni.$on('carModelOk', (option) => {
      form.value.originalModelId = option.id
      form.value.originalModelName = option.modelName

      // 清空车辆信息
      form.value.carId = undefined
      form.value.carLicenseNo = undefined
      form.value.originalSiteModelName = undefined
    })
    // 上门送取车地址选择完成
    uni.$on('mapSelectSuccess', (info) => {
      console.log(info)
      // 处理选择地图后再次回到当前页，需要取得当前操作的类型（取车地址 or 还车地址）
      let mapSuccessType = uni.getStorageSync('showMapLnglatOperateType')
      if (mapSuccessType == 'site') {
        form.value.address = info.address
        form.value.longitude = info.longitude
        form.value.latitude = info.latitude
      } else {
        form.value.returnAddress = info.address
        form.value.returnLongitude = info.longitude
        form.value.returnLatitude = info.latitude
      }
      uni.removeStorageSync('showMapLnglatOperateType')
    })
  })
  onUnload(() => {
    uni.$off('carModelOk')
    uni.$off('mapSelectSuccess')
  })
</script>
<style lang="less" scoped>
  .custom-select {
    position: relative;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    &_input {
      font-size: 30rpx;
      font-weight: 400;
      line-height: 44rpx;
      text-align: right;
      flex: 1;
    }
    &_arrow {
      flex-shrink: 0;
      margin-left: 10rpx;
      margin-top: 10rpx;
    }
  }
  .disabled-select {
    .custom-select_input {
      color: #cdced0;
    }
  }
</style>
